from django.core.cache import cache
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UsernameField
from django.forms import ModelForm, Form
from django.forms import TextInput, PasswordInput, EmailInput
from django.forms import CharField, EmailField
from django.core.exceptions import ValidationError
from .models import User


class LoginForm(Form):
    username = UsernameField(widget=TextInput(attrs={'class': 'form-control'}))
    password = CharField(widget=PasswordInput(attrs={'class': 'form-control'}))


class RegisterForm(ModelForm):

    email = EmailField(widget=EmailInput(attrs={'class': 'form-control', 'id':'email'}))
    captcha = CharField(widget=TextInput(attrs={'class': 'form-control'}))
    username = UsernameField(widget=TextInput(attrs={'class': 'form-control'}))
    password = CharField(widget=PasswordInput(attrs={'class': 'form-control'}))

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            self.add_error('email', "邮箱已存在!")
        return email

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) < 4:
            self.add_error('username', "用户名长度至少为4!")
        if User.objects.filter(username=username).exists():
            self.add_error('username', "用户名已存在!")
        return username

    def clean_captcha(self):
        email = self.cleaned_data['email']
        captcha = self.cleaned_data['captcha']
        if captcha != cache.get(email):
            self.add_error('captcha', "验证码错误!")
        return captcha

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ["username", "email"]
